<?php

namespace app\admin\service;

use app\admin\validate\WebsiteLinksValidate;
use support\spark\exception\ApiException;
use support\spark\model\system\WebsiteLinks;

class LinksService
{
    /**
     * 获取友情链接
     * @param $param
     * @return array
     * @throws \think\db\exception\DbException
     */
    public function getList($param)
    {
        $limit = $param['limit'];
        $name = $param['name'];

        $where = [];
        if (!empty($name)) {
            $where[] = ['name', 'like', '%' . $name . '%'];
        }

        $websiteLinksModel = new WebsiteLinks();
        $list=$websiteLinksModel->getPaginateList($where,['*'],['id'=>'desc']);
        return dataReturn(0, 'success', $list);
    }

    /**
     * 添加友链
     * @param $param
     * @return array
     */
    public function addLinks($param)
    {
        // 检验完整性
        $validate = new WebsiteLinksValidate();
        if (!$validate->check($param)) {
            throw  new ApiException($validate->getError(),-1);
        }

        $websiteLinksModel = new WebsiteLinks();
        $has = $websiteLinksModel->checkUnique([
            'name' => $param['name']
        ]);

        if (!empty($has)) {
            throw  new ApiException('友链标题已经存在',-1);
        }

        $param['create_time'] = now();
        $param['update_time'] = now();
         $websiteLinksModel->insertOne($param);
         return  dataReturn(0,'添加成功');
    }

    /**
     * 编辑友链
     * @param $param
     * @return array
     */
    public function editLinks($param)
    {
        // 检验完整性
        $validate = new WebsiteLinksValidate();
        if (!$validate->check($param)) {
            throw  new ApiException($validate->getError(),-1);
        }
        $websiteLinksModel = new WebsiteLinks();

        $where[] = ['id', '<>', $param['id']];
        $where[] = ['name', '=', $param['name']];
        $has = $websiteLinksModel->checkUnique($where);
        if (!empty($has)) {
            throw  new ApiException('友链标题已经存在',-1);
        }
       $websiteLinksModel->updateById($param, $param['id']);
        return  dataReturn(0,'编辑成功');
    }
}